package superpay

import (
    "errors"
	"thirdpaysdk/core"
	"thirdpaysdk/utils/signature"
	"thirdpaysdk/utils/mapstruct"
)

type QueryReq struct {
	Service      string   `json:"service"`             
	MchId        string   `json:"mch_id"`           
	Charset      string   `json:"charset"`   
	SignType     string   `json:"sign_type"`
	Sign         string   `json:"sign"`            
	Memo         string   `json:"memo,omitempty"`
	Version      string   `json:"version"`      
	StartTime    string   `json:"start_time"`    //开始时间    
	EndTime      string   `json:"end_time"`      //结束时间
	MchOrderNo   string   `json:"mch_order_no"`
	InnerTradeNo string   `json:"inner_trade_no"`    
	TradeType    string   `json:"trade_type"`    
}

type QueryRsp struct {
	Status   string `json:"status"`
	Message  string `json:"message"`
	Data    string `json:"data"`
}

func Query(service,mchId,appSecret,startTime,endTime,mchOrderNo,innerTradeNo,tradeType string) (QueryRsp,error){
	
	url := "https://gate.supaytechnology.com/api/gateway/merchant/order"
	client := core.GetPayJSONClient("POST", url)
	var rsp QueryRsp
	var req = new(QueryReq)
	//
	req.Service = "create_instant_trade"
	req.MchId = mchId
	req.Charset = "UTF-8"
	req.SignType = "MD5"
	req.Memo = ""
	req.Version = "1.0"
	//
	req.StartTime = startTime
	req.EndTime = endTime
	req.MchOrderNo = mchOrderNo
	req.InnerTradeNo = innerTradeNo
	req.TradeType = tradeType
	params := mapstruct.Struct2Map(req, "json")
	req.Sign = signature.SuperPayMakeSign(params, appSecret)
	_, err := client.PayJsonExcute(req, &rsp)
    if err != nil {
		return rsp, err
	}
	if rsp.Status != "T" {
	    returnMsg := rsp.Message
		return rsp, errors.New(returnMsg)
	}
	// 校验回执签名
	/*
	rspMap :=  mapstruct.Struct2Map(rsp, "json")
	sign := signature.SuperPayMakeSign(rspMap, appSecret)
	if rsp.Data.Sign != sign {
		err = errors.New("response sign err")
		return rsp, err
	}
	*/
	return rsp, nil
}
